<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Dao\BusinessDao;
use App\Dao\ScanOrderDao;

use App\Dao\UserDao;
use App\Exception\CustomException;
use App\Job\BusinessMoneyJob;
use App\Job\IntegralJob;
use App\Job\ScanOrderTimeOutJob;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;


use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 线下扫码订单服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\User
 */
class ScanOrderService  extends Service
{
    /**
     * 积分类型：收入
     *
     * @var int
     */
    const INTEGRAL_INCOME = 1;

    /**
     * 积分类型：支出
     *
     * @var int
     */
    const INTEGRAL_EXPEND = 2;

    /**
     * 积分状态：消费
     *
     * @var int
     */
    const INTEGRAL_STATUS_CONSUME = 1;

    /**
     * 积分状态：分润
     *
     * @var int
     */
    const INTEGRAL_STATUS_RETAIL  = 2;

    /**
     * 订单状态：已关闭
     *
     * @var int
     */
    const STATUS_CLOSE = 5;

    /**
     * @Inject
     * @var ScanOrderDao
     */
    public $scan_order_dao;

    /**
     * @Inject
     * @var PingPpService
     */
    private $ping_service;

    /**
     * @Inject
     * @var IntegralDetailService
     */
    private $integral_detail_service;

    /**
     * @Inject
     * @var BusinessDao
     */
    private $business_dao;

    /**
     * @Inject
     * @var UserDao
     */
    private $user_dao;

    /**
     * 关闭线下扫码订单
     *
     * @author 张昊(2396675557@qq.com)
     * @param string $order_no
     * @param int $status
     * @param string $remark
     */
    public function closeOrder(string $order_no, int $status, string $remark = '')
    {
        Db::beginTransaction();
        try {
            $order = $this->scan_order_dao->first([
                'order_no' => $order_no
            ]);
            if (!$order) throw new CustomException('ORDER.NOT_EXIST');
            if ($order->status !== $this->scan_order_dao::STATUS_UNPAID) throw new CustomException('ORDER.STATUS_EXCEPTION');
            $order->status = $status;
            $order->remark = $remark;
            if (!$order->save()) {
                throw new CustomException('ORDER.UPDATE_FAIL');
            }
            Db::commit();
        }
        catch (CustomException $e) {
            Db::rollBack();
            $this->logger('order')->error($e->getMessage(), ['closeOrder']);
            $this->error('');
        }
        catch (\Exception $e) {
            Db::rollBack();
            $this->error('COMMON.SYSTEM_ERROR');
        }
    }

    /**
     * 支付
     * @param array $params
     * @return mixed
     */
    public function pay(array $params)
    {
        $order_no = (string)$this->container->get(IdGeneratorInterface::class)->generate();


        $this->scan_order_dao->createOrder($order_no, $params);
        $result = [
            'amount' => $params['amount'],
            'order_no' => $order_no,
        ];

        $extra = !empty($params['openid']) ? ['open_id' => $params['openid']] :[];

        $payment = $this->ping_service->scan_pay($result, $params['channel'], '扫码支付','线下堂食支付', $extra);

        return [
            'payment' => $payment,
            'order_no' => $order_no
        ];
    }

    /**
     * 线下扫码回调
     * @param $params
     */
    public function pingNotify( $params )
    {
        $where['order_no'] = substr($params['order_no'],4);
        $where['status'] = $this->scan_order_dao::STATUS_UNPAID;
        $order = $this->scan_order_dao->first($where);
        if(!$order) {
            return false;
        }
        $order->status = 1;
        $order->trade_id = $params['transaction_no'];
        $order->updated_at = time();
        if( $order->save() ) {
            $business = $this->business_dao->getBusinessFirst(['id'=>$order['business_id']]);

            $this->user_dao->increment($order['user_id'],$order['amount'],'cumulatived_money');

            $this->integral_detail_service->integral_detail_dao->create([
                'user_id' => $order->user_id,
                'status' => self::INTEGRAL_STATUS_CONSUME,
                'type' => self::INTEGRAL_INCOME,
                'num' => $order['amount'],
                'remark' => '兑换商品',
                'order_no' => $order['order_no'],
                'goods_name' => $business['name'],
                'goods_pic' => $business['logo'],
                'amount' => $order['amount'],
            ]);

            $this->driver->push(new BusinessMoneyJob( $order['order_no'] ));

            $this->driver->push(new IntegralJob( $order->user_id ));

           // $this->money_service->ScanBusinessBonus($order['order_no']);
            //$this->driver->push(new BusinessMoneyJob( $order['order_no'] ));

        }
    }
}